package com.wang.singleton;

public class LazySingleton {

    public static void main(String[] args) {
//        LazySingleton singleton = LazySingleton.getInstance();
//        LazySingleton singleton1 = LazySingleton.getInstance();
//
//        System.out.println(singleton == singleton1);

        new Thread(() -> {
            LazySingleton singleton = LazySingleton.getInstance();
            System.out.println(singleton);
        }).start();
        new Thread(()->{
            LazySingleton singleton = LazySingleton.getInstance();
            System.out.println(singleton);
        }).start();
    }

    //volatile 保证编译时的顺序
    private volatile static LazySingleton singleton= null;

    private LazySingleton(){}

    public static LazySingleton getInstance(){
        if(singleton == null){
            synchronized(LazySingleton.class){ //加锁防止多线程下生成多个实例
                if(singleton == null){
                    singleton = new LazySingleton();
                }
            }

        }
        return singleton;
    }
}
